package  
{
	import flash.display.MovieClip;
	import flash.media.Microphone;
	import flash.system.Security;
	import flash.system.SecurityPanel;
	import flash.events.*;
	import flash.media.SoundMixer;
	import flash.utils.ByteArray;
	
	/**
	 * ...
	 * @author Felix Fleiß, Martina Rasch
	 */
	
	 //this class is a mess
	public class FFT extends MovieClip
	{
		var mic:Microphone; //Reference to the user's audio input device 
		//should store audio input
		var byte:ByteArray = new ByteArray();

		//values needed for calculation
		var highest:int = 0;
		var samplerate:int = 192000;
		var bsize:int = 65536;
		
		var notes = new Array("c'","des'",   "d'",  "es'",   "e'",   "f'", "fes'",   "g'",  "as'",   "a'",   "b'",   "h'", "c''");
		var freq = new Array(261.63, 277.18, 293.66, 311.13, 329.63, 349.23, 369.99, 392.00, 415.30, 440.00, 466.16, 493.88, 523.25);
		
		var lowestFreqToNote:Number = (69 + 12*Math.log(freq[0] / 440.0));
		var highestFreqToNote:Number = (69 + 12*Math.log(freq[freq.length-1] / 440.0));
		var tolerance:Number = 2;
		var tempValue:Number = 0;
		var highestValue:Number = 0;
		
		
		public function FFT()
		{
			mic = Microphone.getMicrophone();
			//to show an annoying option menu
			//Security.showSettings(SecurityPanel.MICROPHONE);
			//can be called with the argument false to stop the redirect to the speaker, but then no input is detected anymore (why?)
			mic.setLoopBack(); 
			//to suppress the recording of the output of the speakers
			mic.setUseEchoSuppression(true);
			this.addEventListener(Event.ENTER_FRAME, onMicActivity);
		}
		
		public function onMicActivity(event:Event):void
		{
			//this should detect the frequency with the highest amplitude, but the byte array doesn't save any values
			SoundMixer.computeSpectrum(byte, true, 0);
			for (var i:int = 0; i < 512; i++) {
				tempValue = byte.readFloat();
				if (tempValue > highestValue)
				{
					highest = i;
					highestValue = tempValue;
				}
			}
			trace(highest);
			trace("hallo");
		}
		
		public function getNote():int
		{
			//currently used to move the player, based on the loudness of the input
			return mic.activityLevel*100;
		}
		
		//not in use yet as nothing works
		function mapFrequencyToNote(freq:Number):Number
		{
			return ((69 + 12*Math.log(freq / 440.0) - lowestFreqToNote) / (highestFreqToNote - lowestFreqToNote));
		}
		
	}

}